<?php

/* David Voong
 * CS 143 - Spring 2012
 * Project 1A
 * calculator.php
 */

if (isset($_GET['expr']) && $_GET['expr'] != '') {
	$expr = str_replace(" ", "", $_GET['expr']);
	
	// handles floating points in forms 123.123, .123, and 123.
	if (preg_match('/^(-?([0-9]+\.?[0-9]*)|(\.[0-9]+))([\*\/+-]-?(([0-9]+\.?[0-9]*)|(\.[0-9]+)))*$/', $expr)) {
			// check for division by zero
			if (preg_match('/\/((0+\.?0*)|(\.?0*))?[\*\/+-]/', $expr) ||
				preg_match('/\/((0+\.?0*)|(\.?0*))?$/', $expr)) {
					$result = "Division by zero";
			} else {
				$expr2 = str_replace("--", "- -", $expr);
				eval('$result = '.$expr2.';');
			}
			
	} else {
			$error = true;
	}
}
?>
<!doctype html>
<html>
<head>
	<meta charset="utf-8">
	<title>Calculator</title>
	<style type="text/css">
	* {
		padding: 0;
		margin: 0;
	}
	body {
		margin: 50px;
		font-family: arial, sans-serif;
	}
	h1 {
		text-align: center;
		margin-bottom: 20px;
	}
	#main {
		width: 700px;
		margin: 0 auto;
		background: #eee;
		padding: 20px;
	}
	input#expr {
		border: 1px #000 solid;
		font: normal 30px "Courier New", courier, monospace;
		width: 568px;
		height: 40px;
		float: left;
		margin: 0 10px 30px 0;
	}
	input#submit {
		border: 1px #aaa solid;
		background: #ccc;
		font: bold 18px/40px arial, sans-serif;
		height: 40px;
		width: 120px;
	}
	input#submit:hover {
		cursor: pointer;
	}
	input#submit:active {
		background: #ddd;
		color: #555;
	}
	h2 {
		clear: both;
		border-bottom: 1px #555 solid;
		margin-bottom: 15px;
	}
	p {
		margin-bottom: 10px;
	}
	p#res {
		font: normal 30px "Courier New", courier, monospace;
		margin: 0;
	}
	p#error {
		font-size: 22px;
	}
	p#error b {
		font-size: 18px;
		color: red;
	}
	ul#f {
		color: #aaa;
		font: normal 11px arial, sans-serif;
		clear: both;
		width: 740px;
		margin: 10px auto;
		text-align: right;
	}
	ul#f li {
		display: inline;
		margin-left: 10px;
	}
	</style>
</head>
<body>
<h1>Calculator</h1>
<div id="main">
	<p>Enter your expression below:</p>
	<form method="GET">
		<input type="text" id="expr" name="expr" value="<?php if(isset($_GET['expr'])) echo $_GET['expr']; ?>"/>
		<input type="submit" id="submit" value="Calculate" />
	</form>
	<?php if (isset($result)): ?>
	<h2>Result</h2>
	<p id="res"><?php echo $expr . " = " . $result; ?></p>
	<?php endif; ?>
	
	<?php if (isset($error)): ?>
	<h2>Result</h2>
	<p id="error"><b>Invalid input expression:</b> <?php echo htmlspecialchars($_GET['expr']); ?></p>
	<?php endif; ?>
</div>
<ul id="f">
	<li>CS 143 - Spring 2012</li>
	<li>Project 1A</li>
	<li>David Voong</li>
</ul>
</body>
</html>